package com.homedo.odin.solution.service.bizservice.mng;

import com.github.pagehelper.PageInfo;
import com.homedo.core.common.base.dto.Meta;
import com.homedo.core.common.exception.BizException;
import com.homedo.core.common.util.BeanUtils;
import com.homedo.core.common.util.ShortUrlHelper;
import com.homedo.odin.solution.contract.mng.request.comment.ReplyUserCommentRequestBean;
import com.homedo.odin.solution.contract.mng.request.comment.UserCommentListRequestBean;
import com.homedo.odin.solution.contract.mng.response.comment.UserCommentDetailResponseBean;
import com.homedo.odin.solution.contract.pc.UserCommentListResponseBean;
import com.homedo.odin.solution.enumcode.basic.ColumnTypeEnum;
import com.homedo.odin.solution.enumcode.column.SpecialColumnStatusEnum;
import com.homedo.odin.solution.enumcode.comment.ColumnCommonContant;
import com.homedo.odin.solution.enumcode.comment.UserCommentStatus;
import com.homedo.odin.solution.enumcode.user.ReplyStatusEnum;
import com.homedo.odin.solution.model.dto.PcAccountInfo;
import com.homedo.odin.solution.model.dto.ShortMessageBean;
import com.homedo.odin.solution.model.entity.ExpertProfile;
import com.homedo.odin.solution.model.entity.Solution;
import com.homedo.odin.solution.model.entity.SpecialColumn;
import com.homedo.odin.solution.model.entity.Specification;
import com.homedo.odin.solution.model.entity.UserComment;
import com.homedo.odin.solution.service.ExpertProfileServiceImpl;
import com.homedo.odin.solution.service.SolutionServiceImpl;
import com.homedo.odin.solution.service.SpecialColumnServiceImpl;
import com.homedo.odin.solution.service.SpecificationServiceImpl;
import com.homedo.odin.solution.service.UserCommentServiceImpl;
import com.homedo.odin.solution.service.common.HomedoService;
import java.util.Date;
import java.util.List;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author: ZhangLei
 * @date: 2018/4/9
 * @Description:
 */
@Service
public class MngUserCommentService {

    @Autowired
    private UserCommentServiceImpl userCommentService;

    @Autowired
    private SpecialColumnServiceImpl specialColumnService;

    @Autowired
    private SolutionServiceImpl solutionService;

    @Autowired
    private HomedoService homedoService;

    @Autowired
    private ExpertProfileServiceImpl expertProfileService;

    @Autowired
    private SpecificationServiceImpl specificationService;

    private final static Logger logger = LoggerFactory.getLogger(MngUserCommentService.class);

    /**
     * 查看评论详情
     */
    public UserCommentDetailResponseBean queryUserCommentDetail(Long commentId) {
        UserComment userComment = userCommentService.selectOne(commentId);
        if (userComment == null) {
            throw new BizException(Meta.CODE_451.getCode(), "评论不存在");
        }
        //评论已删除判断
        if (SpecialColumnStatusEnum.DELETED.getDbValue().equals(userComment.getAuditStatus())) {
            throw new BizException(Meta.CODE_451.getCode(), "评论已删除");
        }

        UserCommentDetailResponseBean userCommentDetailResponse = BeanUtils
                .transfrom(UserCommentDetailResponseBean.class, userComment);
        return userCommentDetailResponse;
    }


    /**
     * 条件查询评论列表
     */
    public UserCommentListResponseBean queryUserCommentList(UserCommentListRequestBean requestBean) {
        Long startDate = requestBean.getCreateStartDate();
        Long endDate = requestBean.getCreateEndDate();

        Date createStartTime = null;
        Date createEndTime = null;
        if (startDate != null && endDate != null) {
            if (startDate > endDate) {
                throw new BizException(Meta.CODE_451.getCode(), "起始时间参数非法");
            }
            createStartTime = new Date(startDate);
            createEndTime = new Date(endDate);
        }
        PageInfo<UserComment> pageInfo = userCommentService
                .queryUserCommentListByParm(requestBean, createStartTime, createEndTime);

        List<UserComment> list = pageInfo.getList();
        if (CollectionUtils.isEmpty(list)) {
            return null;
        }

//        List<UserCommentResponseBean> resultList = new ArrayList<UserCommentResponseBean>();
//        for (UserComment userComment : list) {
//            UserCommentResponseBean userCommentResponse = BeanUtils.transfrom(UserCommentResponseBean.class, userComment);
//            resultList.add(userCommentResponse);
//        }

        UserCommentListResponseBean responseBean = BeanUtils.transfrom(UserCommentListResponseBean.class, pageInfo);
        return responseBean;
        //PageResponse<UserCommentResponseBean>  pageResponse = new PageResponse<>();
        //BeanUtils.copyProperties(pageResponse,pageInfo);
        //return pageResponse;
    }


    /**
     * 审核用户评论通过
     */
    public void auditUserCommentSuccess(Long commentId) {
        UserComment userComment = userCommentService.selectOne(commentId);
        if (userComment == null) {
            throw new BizException(Meta.CODE_451.getCode(), "评论不存在");
        }

        if (!UserCommentStatus.PENDINGAUDIT.getDbValue().equals(userComment.getAuditStatus())) {
            throw new BizException(Meta.CODE_451.getCode(), "该评论不是待审核状态");
        }

        if (UserCommentStatus.DELETED.getDbValue().equals(userComment.getAuditStatus())) {
            throw new BizException(Meta.CODE_451.getCode(), "该评论已删除");
        }

        //修改为审核通过
        userCommentService.auditUserCommentSuccess(commentId);

        if (ColumnTypeEnum.SPECIAL_COLUMN.getDbValue() == userComment.getType().intValue() ||
                ColumnTypeEnum.VIDEO_COLUMN.getDbValue() == userComment.getType().intValue()) {
            //增加该栏目的评论量
            specialColumnService.addSpecialColumnCommentCount(userComment.getColumnId());
        }

        if (ColumnTypeEnum.SOLUTION.getDbValue() == userComment.getType().intValue()) {
            //方案
            Solution solution = solutionService.getSolution(userComment.getColumnId());
            if (solution != null) {
                //发短信
                ShortMessageBean shortMessageBean = new ShortMessageBean();
                PcAccountInfo userMessageInfo = homedoService.getUserMessageInfo(solution.getUserId());
                String phone = null == userMessageInfo ? "" : userMessageInfo.getMobile();
                //String url = "http://172.16.220.152:3001/solutions/detail/"+SOLUTION.getSolutionId().toString()+".html";//测试环境
                String url = "http://msolution.homedo.com/solutions/detail/" + solution.getSolutionId().toString()
                        + ".html";//正式环境
                String content =
                        "【河姆渡】尊敬的" + solution.getUserName() + "，有人刚刚评论了您的方案“" + solution.getSolutionName() + "”，详情请点击"
                                + ShortUrlHelper.convertToSINAShortUrl(url);
                shortMessageBean.setAccountId(solution.getUserId());
                shortMessageBean.setPhone(phone);
                shortMessageBean.setContent(content);
                try {
                    homedoService.sendShortMessage(shortMessageBean);
                } catch (Exception e) {
                    logger.error("请求平台发送短息接口异常", e);
                }
            }
        }
    }


    /**
     * 删除评论
     */
    public void updateUserComment(Long commentId) {
        UserComment userComment = userCommentService.selectOne(commentId);

        if (userComment == null) {
            throw new BizException(Meta.CODE_451.getCode(), "评论不存在");
        }

        if (UserCommentStatus.DELETED.getDbValue().equals(userComment.getAuditStatus())) {
            throw new BizException(Meta.CODE_451.getCode(), "该评论已经删除了");
        }

        userCommentService.updateUserComment(commentId);
    }


    /**
     * 回复评论
     */
    public void replyUserComment(Long commentId, ReplyUserCommentRequestBean requestBean) {
        UserComment userComment = userCommentService.selectOne(commentId);
        if (userComment == null) {
            throw new BizException(Meta.CODE_451.getCode(), "该评论不存在");
        }

        Integer replyPerson = requestBean.getReplyPerson();

        //评论人是作者自己
        if (replyPerson.equals(ColumnCommonContant.REPLY_PERSON_IS_AUTHOR)) {
            if (ColumnTypeEnum.SOLUTION.getDbValue() == userComment.getType().intValue()) {
                //方案
                Solution solution = solutionService.getSolution(userComment.getColumnId());
                if (solution == null) {
                    throw new BizException(Meta.CODE_451.getCode(), "该方案不存在");
                }
                userComment.setReplyPerson(solution.getUserName());
                ExpertProfile expert = expertProfileService.getExpert(solution.getUserId());
                if (expert != null) {
                    userComment.setReplyAvatar(expert.getAvatar());
                }
            } else if (ColumnTypeEnum.SPECIFICATION.getDbValue() == userComment.getType().intValue()) {
                //规范
                //如果评价类型是规范，columnId为规范Uid 如规范146981263226834944
                Specification specification = specificationService
                        .getSpecificationBySpecificationId(userComment.getColumnId());
                if (specification == null) {
                    throw new BizException(Meta.CODE_451.getCode(), "该行业规范不存在");
                }
                userComment.setReplyPerson(specification.getUserName());
                ExpertProfile expert = expertProfileService.getExpert(specification.getUserId());
                if (expert != null) {
                    userComment.setReplyAvatar(expert.getAvatar());
                }
            } else {
                //栏目
                SpecialColumn specialColumn = specialColumnService.getSpecialColumn(userComment.getColumnId());
                if (specialColumn == null) {
                    throw new BizException(Meta.CODE_451.getCode(), "该栏目不存在");
                }

                userComment.setReplyPerson(specialColumn.getExpertName());
                //获取专家信息
                ExpertProfile expert = expertProfileService.getExpert(specialColumn.getExpertId());
                if (expert != null) {
                    userComment.setReplyAvatar(expert.getAvatar());//回复人头像
                }
            }
        } else {
            userComment.setReplyPerson(ColumnCommonContant.DEFAULT_REPLY_PERSON);
        }

        userComment.setReplyStatus(ReplyStatusEnum.REPLY.getDbValue());
        userComment.setReplyContent(requestBean.getReplyContent());
        userComment.setReplyTime(new Date());
        userCommentService.replyUserComment(userComment);
    }
}
